<template lang="pug">
  div.cpt-tree
    tree-node(v-for="(item,index) in treeData" :key="item" :nodeData="item" @on-change="changeHandler" @on-toggle="toggleHandler")
</template>
<script>
import treeNode from './node';
import * as commonUtils from '../../utils/common-utils';
import _ from 'lodash';

export default {
  components: {
    treeNode
  },
  props: {
    data: {
      type: Array,
      default() {
        return [];
      }
    }
  },
  data() {
    return {
      treeData: this.data
    };
  },
  watch: {
    data(nv) {
      this.treeData = nv;
    }
  },
  methods: {
    changeHandler(nodeData) {
      this.treeData = this.selectNode(_.cloneDeep(this.treeData), nodeData);
      this.$emit('on-change', nodeData);
    },
    toggleHandler(nodeData) {
      this.treeData = commonUtils.recurseItem(this.treeData, item => {
        if (nodeData.id === item.id) {
          item.open = !item.open;
        }
        return item;
      });
    },
    // 处理根据子节点修改父节点选择状态
    selectParentNode(treeData) {
      return _.map(treeData, item => {
        if (!_.isEmpty(item.children)) {
          item.children = this.selectParentNode(item.children);
          item.selected = _.every(item.children, citem => citem.selected);
        }
        return item;
      });
    },
    // 处理当前所选节点和子节点选择状态
    selectNode(treeData, nodeData) {
      const data = _.map(treeData, item => {
        if (item.id === nodeData.id) {
          item.selected = !item.selected;
          if (!_.isEmpty(item.children)) {
            item.children = commonUtils.recurseItem(item.children, nitem => {
              nitem.selected = item.selected;
              return nitem;
            });
          }
        } else {
          !_.isEmpty(item.children) && this.selectNode(item.children, nodeData);
        }
        return item;
      });
      return this.selectParentNode(data);
    },
    // 获取选择的节点
    getSelection() {
      const selections = [];
      commonUtils.recurseItem(_.cloneDeep(this.treeData), item => {
        if (item.selected) {
          selections.push(item);
        }
      });
      return selections;
    }
  }
};
</script>

<style lang="less">
.cpt-tree {
  .cpt-tree-node {
    margin-left: 1rem;
    .handler {
      padding: 0.3rem 0;
      & > .icon-spander {
        cursor: pointer;
        width: 20px;
        display: inline-block;
        font-size: 16px;
        vertical-align: middle;
      }
    }
  }
}
</style>
